import axios from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { message } from 'ant-design-vue'
import type { ApiResponse } from '@/types/api'

const http = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000
})

// 请求拦截：附带 Token、进度条
http.interceptors.request.use(
  (config) => {
    NProgress.start()
    const token = localStorage.getItem('token')
    if (token) {
      ;(config.headers as any) = (config.headers as any) || {}
      ;(config.headers as any).Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    NProgress.done()
    return Promise.reject(error)
  }
)

// 响应拦截：统一错误处理与返回结构
http.interceptors.response.use(
  (resp) => {
    NProgress.done()
    const data = resp.data as ApiResponse<unknown> | Blob | undefined
    // 文件下载等非标准结构，直接返回
    if (data === undefined || data instanceof Blob) {
      return resp
    }
    // 标准后端返回结构
    if (typeof (data as any).code === 'number') {
      const api = data as ApiResponse<any>
      if (api.code === 0) {
        return resp
      }
      // 非成功：统一提示
      message.error(api.message || '请求失败')
      return Promise.reject(new Error(api.message || '请求失败'))
    }
    return resp
  },
  (error) => {
    NProgress.done()
    let msg = '网络异常，请稍后重试'
    if (error.response) {
      const { status } = error.response
      if (status === 401) msg = '未授权或登录已过期'
      else if (status === 403) msg = '没有权限访问该资源'
      else if (status === 404) msg = '资源不存在'
      else if (status >= 500) msg = '服务器开小差了'
    } else if (error.code === 'ECONNABORTED') {
      msg = '请求超时，请稍后重试'
    }
    message.error(msg)
    if (error.response && error.response.status === 401) {
      try {
        localStorage.removeItem('token')
        localStorage.removeItem('profile')
      } catch {}
      // 避免重复跳转
      if (typeof window !== 'undefined' && !((window as any).__AUTH_REDIRECTING__)) {
        ;(window as any).__AUTH_REDIRECTING__ = true
        setTimeout(() => {
          try { (window as any).__AUTH_REDIRECTING__ = false } catch {}
          window.location.href = '/'
        }, 300)
      }
    }
    return Promise.reject(error)
  }
)

export default http


